package com.yc.web;

import org.springframework.core.convert.converter.Converter;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * SpringMVC 自定义类型转换
 */
public class TimeConverter implements Converter<String, Timestamp> {

    public static final String YYYYMMDDHHMM = "yyyy/MM/dd HH:mm";
    public static final String YYYYMMDD = "yyyy/MM/dd";
    public static final String YYYYMMDDHHMMSS = "yyyy/MM/dd HH:mm:ss";

    @Override
    public Timestamp convert(String s) {
        try{
            if (s != null) {
                System.out.println("+++++" + s);
                if(s.matches("\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}")){
                    Date d = new SimpleDateFormat(YYYYMMDDHHMM).parse(s);
                    return new Timestamp(d.getTime());
                }
                // 其他格式日期, 请自行扩展
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
